package cn.milolab.djback.service;

import cn.milolab.djback.bean.response.WechatLoginResponse;
import cn.milolab.djback.bean.entity.Employee;
import cn.milolab.djback.bean.entity.User;
import cn.milolab.djback.conf.business.MiniprogramConfig;
import cn.milolab.djback.conf.jwt.JwtUtil;
import cn.milolab.djback.dao.EmployeeDAO;
import cn.milolab.djback.dao.UserDAO;
import cn.milolab.djback.conf.DjException;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author milowang
 */
@Service
public class LoginService {
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret" +
            "={appsecret}&js_code={jscode}&grant_type=authorization_code";
    @Autowired
    UserDAO userDAO;
    @Autowired
    EmployeeDAO employeeDAO;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    MiniprogramConfig miniprogramConfig;

    public Map<String, Object> login(String code, String avatarUrl) {
        WechatLoginResponse loginResponse = wechatLogin(code);

        User user = userDAO.getUserByOpenid(loginResponse.getOpenid());

        // 如果用户没有创建
        if (user == null) {

            // 创建一个新用户
            user = new User();
            user.setAvatarUrl(avatarUrl);
            user.setOpenid(loginResponse.getOpenid());
            user.setSessionKey(loginResponse.getSession_key());

            // 添加进数据库
            Integer insertResult = userDAO.insertUser(user);
            if (insertResult != 1) {
                throw new RuntimeException("无法创建用户");
            }

            // 更新user对象
            user = userDAO.getUserByOpenid(loginResponse.getOpenid());
        }else{

            // 更新头像
            userDAO.updateUserAvatar(user.getId(), avatarUrl);
        }

        //生成token
        Map<String,Object> claim = new HashMap<>();
        claim.put("userId",user.getId());
        String token = JwtUtil.createToken(claim);

        // 获取社员实体
        Employee employee = employeeDAO.getEmployeeByUserId(user.getId());

        // 构建返回结构
        HashMap<String, Object> result = new HashMap<>(2);
        result.put("user", user);
        result.put("employee", employee);
        result.put("authorization", token);

        return result;
    }

    private WechatLoginResponse wechatLogin(String code) {
        // 构建请求参数
        Map<String, String> requestParam = new HashMap<>(3);
        requestParam.put("appid", miniprogramConfig.getAppid());
        requestParam.put("appsecret", miniprogramConfig.getAppsecret());
        requestParam.put("jscode", code);

        // 发送请求，返回结果
        WechatLoginResponse result;
        try {
            result = restTemplate.getForObject(WX_LOGIN_URL, WechatLoginResponse.class, requestParam);
        } catch (RestClientException e) {
            throw DjException.internalServerError("服务端网络错误");
        }
        if (result == null) {
            throw DjException.internalServerError("登录逻辑异常");
        }
        if (result.getErrcode() != null && result.getErrcode() != 0) {
            throw DjException.requestLogicError("登录口令无效");
        }
        return result;
    }
}
